﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Transactions;
using System.Windows.Forms;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Data.Sql;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using Microsoft.Practices.EnterpriseLibrary.Logging.Filters;
using Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners;
using Microsoft.Practices.EnterpriseLibrary.TransientFaultHandling;
using Quartz;
using Quartz.Impl;
using ExceptionFormatter = Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ExceptionFormatter;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {


            ThreadPool.QueueUserWorkItem((object s) => { GetValue(); }, null);
            ThreadPool.QueueUserWorkItem((object s) => { GetValue(); }, null);

            ThreadPool.QueueUserWorkItem((object s) => { GetValue(); }, null);
        }

        private static void GetValue()
        {
            for (int i = 0; i < 1000000000; i++)
            {
                DataClasses1DataContext dc = new DataClasses1DataContext();
                SqlCommand cmd = new SqlCommand();
                cmd.CommandText =
                    @"select   TypeID      ,EntityID      ,RcopiaID      ,IsDeleted      ,LoggedDate      ,PatientID      ,ErrorText from [DrFirst_RcopiaErrorLog] where 1<>1";
                cmd.Connection = dc.Connection as SqlConnection;
                SqlDataAdapter da = new SqlDataAdapter();
                da.SelectCommand = cmd;
                DataSet ds = new DataSet();
                da.Fill(ds);

                for (int j = 0; j < 10000; j++)
                {
                    DataRow dr = ds.Tables[0].Rows.Add();
                    //dr["ID"] = 0;
                    dr["TypeID"] = 1;
                    dr["EntityID"] = 50667;
                    dr["RcopiaID"] = DBNull.Value;
                    dr["LoggedDate"] = DateTime.Now.AddDays(-269 + i);
                    dr["PatientID"] = 50667;
                    dr["IsDeleted"] = 0;
                    dr["ErrorText"] =
                        "Patient ID = [50667]: FirstName = [Joan], LastName = [Smith], Date of Birth = [], Gender = [F], Zip Code = [84123], Home Phone = [(801) 555-4301] are required by DrFirst.";
                    //dr.SetAdded();
                }

                SqlBulkCopy copy = new SqlBulkCopy("Data Source=.;Initial Catalog=EmptyForTestDemo;Integrated Security=True",
                    SqlBulkCopyOptions.KeepIdentity);
                copy.BulkCopyTimeout = 60000;
                copy.DestinationTableName = "DrFirst_RcopiaErrorLog";
                copy.ColumnMappings.Add("TypeID", "TypeID");
                copy.ColumnMappings.Add("EntityID", "EntityID");
                copy.ColumnMappings.Add("RcopiaID", "RcopiaID");
                copy.ColumnMappings.Add("LoggedDate", "LoggedDate");
                copy.ColumnMappings.Add("IsDeleted", "IsDeleted");
                copy.ColumnMappings.Add("PatientID", "PatientID");
                copy.ColumnMappings.Add("ErrorText", "ErrorText");

                copy.WriteToServer(ds.Tables[0], DataRowState.Added);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            string html = "<table>.............<table>";
            var match = Regex.Match(html, @"\<table\>(?<content>.*)\<table\>");
            string content = match.Groups["content"].Value;

            while (!this.IsHandleCreated)
            {
                Thread.Sleep(100);
            }


            DateTime targetDate = DateTime.Now.AddDays(-60);
            DataClasses1DataContext dc = new DataClasses1DataContext();
            int rowCount = GetRowCount(dc.Connection as SqlConnection);
            using (SqlConnection connection = dc.Connection as SqlConnection)
            {
                if (connection.State != ConnectionState.Open)
                    connection.Open();

                int batchSize = 50000;
                long start = GetMinID(dc);
                while (true)
                {
                    long end = start + batchSize;
                    if (end > rowCount) break;
                    DateTime? loggedDate = GetLoggedDate(connection, start, start + batchSize);
                    if (!loggedDate.HasValue || loggedDate.Value > targetDate)
                    {
                        start = end;
                        continue;
                    }

                    Delete(connection, start, end);
                    start = end;
                }

            }
        }

        private int GetRowCount(SqlConnection connection)
        {
            string sql = @"SELECT OBJECT_NAME(i.id)  TableName, i.rowcnt RowCnt
                    FROM sys.sysindexes i
                    WHERE i.indid in (0,1) AND i.id = object_id('DrFirst_RcopiaErrorLog')
                    ORDER BY i.rowcnt desc";
            if (connection.State != ConnectionState.Open)
                connection.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = sql;
            cmd.Connection = connection;
            DataSet ds = new DataSet();
            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = cmd;
            da.Fill(ds);
            return int.Parse(ds.Tables[0].Rows[0]["Rowcnt"] + "");
        }

        private DateTime? GetLoggedDate(SqlConnection connection, long start, long end)
        {
            string sql =
                "SELECT LoggedDate FROM  DrFirst_RcopiaErrorLog WHERE ID in (SELECT MAX(id) FROM DrFirst_RcopiaErrorLog WHERE id BETWEEN {0} AND {1})";
            sql = string.Format(sql, start, end);
            if (connection.State != ConnectionState.Open)
                connection.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = connection;
            cmd.CommandText = sql;
            DataSet ds = new DataSet();
            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = cmd;
            da.Fill(ds);
            if (ds.Tables[0].Rows.Count == 0) return default(DateTime?);
            return (DateTime)(ds.Tables[0].Rows[0][0]);
        }

        private long GetMinID(DataClasses1DataContext dc)
        {
            return dc.DrFirst_RcopiaErrorLogs.Min(x => x.ID);
        }

        private void Delete(SqlConnection connection, long start, long end)
        {
            string sql =
                "DELETE FROM  DrFirst_RcopiaErrorLog WHERE ID Between {0} and {1}";
            sql = string.Format(sql, start, end);
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = sql;
            if (connection.State != ConnectionState.Open)
                connection.Open();

            cmd.Connection = connection;
            cmd.ExecuteNonQuery();



        }

        static Regex rxColumns = new Regex(@"\A\s*SELECT\s+((?:\((?>\((?<depth>)|\)(?<-depth>)|.?)*(?(depth)(?!))\)|.)*?)(?<!,\s+)\bFROM\b", RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Singleline);
        static Regex rxOrderBy = new Regex(@"\bORDER\s+BY\s+(?!.*?(?:\)|\s+)AS\s)(?:\((?>\((?<depth>)|\)(?<-depth>)|.?)*(?(depth)(?!))\)|[\w\(\)\.])+(?:\s+(?:ASC|DESC))?(?:\s*,\s*(?:\((?>\((?<depth>)|\)(?<-depth>)|.?)*(?(depth)(?!))\)|[\w\(\)\.])+(?:\s+(?:ASC|DESC))?)*", RegexOptions.RightToLeft | RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Singleline);
        static Regex rxDistinct = new Regex(@"\ADISTINCT\s", RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Singleline);

        private void button3_Click(object sender, EventArgs e)
        {
            using (DataClasses1DataContext ctx = new DataClasses1DataContext())
            {
                using (var tx = new System.Transactions.TransactionScope(TransactionScopeOption.Required,
                       new TransactionOptions() { IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted }))
                {

                    var row = ctx.DrFirst_RcopiaErrorLogs.FirstOrDefault(x => x.ID == 1);
                    //  Console.WriteLine(row.IsDeleted);
                }
            }

            using (DataClasses1DataContext ctx = new DataClasses1DataContext())
            {
                using (var tx = new System.Transactions.TransactionScope(TransactionScopeOption.Required,
                       new TransactionOptions() { IsolationLevel = System.Transactions.IsolationLevel.Serializable }))
                {

                    var row = ctx.DrFirst_RcopiaErrorLogs.FirstOrDefault(x => x.ID == 1);
                    //  Console.WriteLine(row.IsDeleted);
                }
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.lookUpEdit1.Properties.ValueMember = "ID";
            this.lookUpEdit1.Properties.DisplayMember = "Name";
            this.lookUpEdit1.Properties.DataSource = Person.GetList();
            this.lookUpEdit1.Properties.AllowNullInput = DevExpress.Utils.DefaultBoolean.True;
        }

        public class Person
        {
            public static IList<Person> GetList()
            {
                var p = new List<Person>();
                p.Add(new Person() { ID = 1, Name = "df" });
                p.Add(new Person() { ID = 2, Name = "df2" });
                return p;
            }

            public int ID { get; set; }
            public string Name { get; set; }
        }

        private void lookUpEdit1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Back)
            {
                this.lookUpEdit1.EditValue = null;
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            string text = @"A    Active PRE4-RP           YES     IOS        N/A         ONLINE
B    Standby PRE4-RP          YES     IOS        N/A         ONLINE
1    4jacket-1                YES     LCDOS      N/A         ONLINE
1/1  2cable-dtcc              NO      LCDOS      N/A         ONLINE
2/1  2cable-dtcc              NO      LCDOS      N/A         ONLINE
3    4jacket-1                YES     LCDOS      N/A         ONLINE
5/0  ubr10k-clc-mc2020v       YES     IOS        N/A         ONLINE
5/1  ubr10k-clc-mc2020v       YES     IOS        N/A         ONLINE
6/0  ubr10k-clc-mc2020v       YES     IOS        N/A         ONLINE
7/0  ubr10k-clc-mc2020v       YES     IOS        N/A         ONLINE
7/1  ubr10k-clc-mc2020v       YES     IOS        N/A         ONLINE
8/0  ubr10k-clc-mc2020v       YES     IOS        N/A         ONLINE   
8/1  ubr10k-clc-mc2020v       YES     IOS        N/A         ONLINE";

            var matches = Regex.Matches(text, @"(?<onlineOrOther>\w+?)(?<s>\s*)$", RegexOptions.Multiline);
            foreach (Match match in matches)
            {
                string d = match.Groups["onlineOrOther"].Value;
                if (d.Contains("\r") || d.Contains("\n") || d.Contains(" "))
                    throw new Exception();
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            string html = @"<p class=""xdct0"">　aaaaaaaaaaaaa“<span class=""zx3"">bbb</span>”ccc</p>";
            string patten = @"<p\s+class=""xdct0"">\s*([^“]*)“<span\s+class=""zx3"">([^<>]*)</span>”([^<]*)</p>";
            Match m = Regex.Match(html, patten);
            if (m.Success)
            {
                Console.WriteLine(m.Groups[1].Value);
                Console.WriteLine(m.Groups[2].Value);
                Console.WriteLine(m.Groups[3].Value);
            }
        }

        private void btnDatabaseBlock_Click(object sender, EventArgs e)
        {
            DatabaseProviderFactory databaseProviderFactory = new DatabaseProviderFactory();
            SqlDatabase database = databaseProviderFactory.Create("EmptyForTestDemo") as SqlDatabase;

            SqlStringAccessor<Patient> accessor = new SqlStringAccessor<Patient>(database, "select * from Dic_Patient", new PatientMapper());
            var ps = accessor.Execute().ToList();
        }

        private void btnRetry_Click(object sender, EventArgs e)
        {
            RetryPolicy retry = new RetryPolicy(new SqlDatabaseTransientErrorDetectionStrategy(), 5, TimeSpan.FromSeconds(4));
            retry.ExecuteAction(() =>
            {
                Console.WriteLine("dddddddddd");
                throw new TimeoutException();
            });

        }

        private void btnException_Click(object sender, EventArgs e)
        {
            var policyDifinitions = new List<ExceptionPolicyDefinition>();
            var myNotifyRethrowExceptionPolicy = new List<ExceptionPolicyEntry>();
            myNotifyRethrowExceptionPolicy.Add(new ExceptionPolicyEntry(typeof(TimeoutException), PostHandlingAction.NotifyRethrow
                , new List<IExceptionHandler>()
                {
                    new LoggingExceptionHandler("General",9000, TraceEventType.Error, "This is logging", 5, typeof(ExceptionFormatter),CreateExceptionLogWriter2()),
                    new ReplaceHandler("NotifyRethrow",typeof(TimeoutException)),
                    //string logCategory, int eventId, TraceEventType severity, string title, int priority, Type formatterType, LogWriter writer
                    
                })
            );

            var myNoneExceptionPolicy = new List<ExceptionPolicyEntry>();
            myNoneExceptionPolicy.Add(new ExceptionPolicyEntry(typeof(TimeoutException)
                , PostHandlingAction.None
                , new List<IExceptionHandler>()
                {
                    new ReplaceHandler("None", typeof(TimeoutException)),
                    new MyExceptionHandler()
                })
            );
            policyDifinitions.Add(new ExceptionPolicyDefinition("myNotifyRethrowExceptionPolicy", myNotifyRethrowExceptionPolicy));
            policyDifinitions.Add(new ExceptionPolicyDefinition("myNoneExceptionPolicy", myNoneExceptionPolicy));

            Exception exceptionToThrow = null;
            ExceptionManager exceptionManager = new ExceptionManager(policyDifinitions);
            exceptionManager.HandleException(new TimeoutException(), "myNoneExceptionPolicy", out exceptionToThrow);
            exceptionManager.HandleException(new TimeoutException(), "myNotifyRethrowExceptionPolicy", out exceptionToThrow);
            exceptionManager.Process(() =>
            {
                throw new TimeoutException();
            }, "myNoneExceptionPolicy");

            //exceptionManager.Process(() =>
            //{
            //    throw new TimeoutException();
            //}, "myNotifyRethrowExceptionPolicy");
        }

        private LogWriter CreateExceptionLogWriter()
        {
            FlatFileTraceListener flatFileTraceListener = new FlatFileTraceListener(@"C:\exceptionFlatLog.log");
            LogSource logSource = new LogSource("ExceptionTestLogSource", new List<TraceListener>() { flatFileTraceListener }, SourceLevels.All);
            //string name, ICollection< string > categoryFilters, CategoryFilterMode categoryFilterMode
            //CategoryFilter categoryFilter = new CategoryFilter("TestFilter", new List<string>() { "ExceptionLoggingCategory" }, CategoryFilterMode.AllowAllExceptDenied);
            LogEnabledFilter logEnableFilter = new LogEnabledFilter("LogEnabledFilter", true);
            LogWriter logWriter = new LogWriter(new List<ILogFilter>() { logEnableFilter }, new List<LogSource>() { logSource }, logSource, "ExceptionLoggingCategory");

            return logWriter;
        }

        private LogWriter CreateExceptionLogWriter2()
        {
            ConsoleTraceListener flatFileTraceListener = new ConsoleTraceListener();
            LogSource logSource = new LogSource("ExceptionTestLogSource", new List<TraceListener>() { flatFileTraceListener }, SourceLevels.All);

            LoggingConfiguration configuration = new LoggingConfiguration();
            configuration.AddLogSource("General", SourceLevels.All, true)
                .AddTraceListener(flatFileTraceListener);
            configuration.SpecialSources.LoggingErrorsAndWarnings.AddTraceListener(flatFileTraceListener);
            LogWriter logWriter = new LogWriter(configuration);

            return logWriter;
        }

        private void btnLogging_Click(object sender, EventArgs e)
        {
            WriteSimpleLogging();
            WriteTraceManager();
        }

        private void WriteSimpleLogging()
        {
            ConsoleTraceListener flatFileTraceListnener = new ConsoleTraceListener();

            //LogSource logSource = new LogSource();
            LoggingConfiguration config = new LoggingConfiguration();

            string categoryName = "Category__________1";
            string categoryName2 = "Category__________2";

            config.AddLogSource(categoryName, SourceLevels.All, true, flatFileTraceListnener);
            //config.Filters.Add(new CategoryFilter("CategoryFilter", new List<string>() { "aa", "bbb"}, CategoryFilterMode.DenyAllExceptAllowed));
            config.Filters.Add(new PriorityFilter("PriorityFilter", -10, 3));

            config.AddLogSource(categoryName2, SourceLevels.All, true, new XmlWriterTraceListener(@"C:\xml.xml"));

            config.SpecialSources.Unprocessed.AddTraceListener(new XmlWriterTraceListener(@"C:\Unprocessedxml.xml"));
            config.SpecialSources.AllEvents.AddTraceListener(new XmlWriterTraceListener(@"C:\AllEventsxml.xml"));
            // config.SpecialSources.AllEvents.AddTraceListener(new ConsoleTraceListener());

            LogWriter logWriter = new LogWriter(config);
            LogEntry logEntry = new LogEntry();
            logEntry.Message = "test  dddddddddddddddddddd ";
            //logEntry.Categories.Add(categoryName);
            //logEntry.Categories.Add(categoryName2);
            logEntry.Priority = 20;

            logWriter.Write(logEntry);

        }

        private void WriteTraceManager()
        {
            ConsoleTraceListener consoleTraceListener = new ConsoleTraceListener();

            //LogSource logSource = new LogSource();
            LoggingConfiguration config = new LoggingConfiguration();

            config.AddLogSource("General", SourceLevels.All, true, consoleTraceListener);

            LogWriter logWriter = new LogWriter(config);
            LogEntry logEntry = new LogEntry();
            logEntry.Message = "test  dddddddddddddddddddd ";
            logEntry.Categories.Add("General");
            logEntry.Priority = 20;

            TraceManager traceManager = new TraceManager(logWriter);
            logWriter.Write(logEntry);
            using (traceManager.StartTrace("General"))
            {
                logWriter.Write(logEntry);
                logWriter.Write(logEntry);
            }
        }

        private void button6_Click(object sender, EventArgs e)
        {
            // construct a scheduler factory
            ISchedulerFactory schedFact = new StdSchedulerFactory();

            // get a scheduler
            IScheduler sched = schedFact.GetScheduler();
            sched.ListenerManager.AddJobListener(new HelloJobListener());
            sched.Start();

            // define the job and tie it to our HelloJob class
            IJobDetail job = JobBuilder.Create<HelloJob>()
                .WithIdentity("myJob", "group1")
                .Build();

            // Trigger the job to run now, and then every 40 seconds
            ITrigger trigger = TriggerBuilder.Create()
              .WithIdentity("myTrigger", "group1")
              .StartNow()
              .WithSimpleSchedule(x => x
                  .WithIntervalInSeconds(2)
                  .RepeatForever())
              .Build();

            sched.ScheduleJob(job, trigger);

            IJobDetail job2 = JobBuilder.Create<HelloJob>()
               .WithIdentity("myJob2", "group2")
               .Build();
            ITrigger trigger2 = TriggerBuilder.Create()
             .WithIdentity("myTrigger2", "group2")
             .StartNow()
             .WithSimpleSchedule(x => x
                 .WithIntervalInSeconds(2)
                 .RepeatForever())
             .Build();
            sched.ScheduleJob(job2, trigger2);
        }

        private void btnQuartzWrong_Click(object sender, EventArgs e)
        {
            // construct a scheduler factory
            ISchedulerFactory schedFact = new StdSchedulerFactory();

            // get a scheduler
            IScheduler sched = schedFact.GetScheduler();
            sched.Start();

            // define the job and tie it to our HelloJob class
            IJobDetail job = JobBuilder.Create<WrongHelloJob>()
                .WithIdentity("myJob", "group1")
                .Build();

            // Trigger the job to run now, and then every 40 seconds
            ITrigger trigger = TriggerBuilder.Create()
              .WithIdentity("myTrigger", "group1")
              .StartNow()
              .WithSimpleSchedule(x => x
                  .WithIntervalInSeconds(6)
                  .RepeatForever())
              .Build();

            sched.ScheduleJob(job, trigger);

            //IJobDetail job2 = JobBuilder.Create<WrongHelloJob>()
            //   .WithIdentity("myJob2", "group2")
            //   .Build();
            //ITrigger trigger2 = TriggerBuilder.Create()
            // .WithIdentity("myTrigger2", "group2")
            // .StartNow()
            // .WithSimpleSchedule(x => x
            //     .WithIntervalInSeconds(2)
            //     .RepeatForever())
            // .Build();
            //sched.ScheduleJob(job2, trigger2);
        }

        private void btnInterrupt_Click(object sender, EventArgs e)
        {
            IScheduler sched = StdSchedulerFactory.GetDefaultScheduler();
            if (sched.IsStarted)
            {
                var jobs = sched.GetCurrentlyExecutingJobs();
                foreach (var context in jobs)
                {
                    sched.Interrupt(context.JobDetail.Key);
                    //if (context.JobInstance is IInterruptableJob)
                    //{
                    //    (context.JobInstance as IInterruptableJob).Interrupt();
                    //}
                }
            }
        }
    }

    internal class WrongHelloJob : IJob
    {
        public static string NeedToBeExcuted = "NeedToBeExcuted";
        private static readonly object _lock = new object();

        public void Execute(IJobExecutionContext context)
        {
            if (GetCurrentExecutingCount(context) <= 1)
            {
                Console.WriteLine("WrongHelloJob Job Ignored" + DateTime.Now);
                return;
            }

            Console.WriteLine(string.Format("Before Sleep WrongHelloJob Job in {0}=", context.JobDetail.Key.Group) + DateTime.Now);
            Thread.Sleep(8 * 1000);
            Console.WriteLine(string.Format("After Sleep WrongHelloJob Job in {0}=", context.JobDetail.Key.Group) + DateTime.Now);
        }

        private static int GetCurrentExecutingCount(IJobExecutionContext context)
        {
            lock (_lock)
            {
                return context.Scheduler
                      .GetCurrentlyExecutingJobs()
                      .Count(
                          x =>
                              x.JobDetail.JobDataMap.ContainsKey(HelloJob.NeedToBeExcuted) &&
                              x.JobDetail.JobDataMap[NeedToBeExcuted].ToString() == "1");
            }
        }

    }

    internal class HelloJob : IJob, IInterruptableJob
    {
        public static string NeedToBeExcuted = "NeedToBeExcuted";
        private static object _lock = new object();

        public void Execute(IJobExecutionContext context)
        {
            lock (_lock)
            {
                if (context.JobDetail.JobDataMap.ContainsKey(NeedToBeExcuted) &&
                    context.JobDetail.JobDataMap[NeedToBeExcuted].ToString() == "0")
                {
                    Console.WriteLine("Hello Job Ignored" + DateTime.Now);
                    return;
                }
            }

            Console.WriteLine(string.Format("Before Hello Job in {0}=", context.JobDetail.Key.Group) + DateTime.Now);
            int loop = 0;

            while (loop < 8)
            {
                if (_Interrupted)
                {
                    Console.WriteLine(string.Format("Hello Job is Interrupted  in {0}=", context.JobDetail.Key.Group) + DateTime.Now);
                    return;
                }
                Thread.Sleep(1000);
                loop++;
            }

            Console.WriteLine(string.Format("After Hello Job in {0}=", context.JobDetail.Key.Group) + DateTime.Now);
        }

        private bool _Interrupted = false;
        public void Interrupt()
        {
            _Interrupted = true;
        }
    }

    public class HelloJobListener : IJobListener
    {
        public static string NeedToBeExcuted = "NeedToBeExcuted";
        private static object _lock = new object();
        public void JobToBeExecuted(IJobExecutionContext context)
        {
            lock (_lock)
            {
                int count = context.Scheduler
                    .GetCurrentlyExecutingJobs()
                    .Count(
                        x =>
                            x.JobDetail.JobDataMap.ContainsKey(HelloJob.NeedToBeExcuted) &&
                            x.JobDetail.JobDataMap[NeedToBeExcuted].ToString() == "1");
                if (count > 0)
                {
                    context.JobDetail.JobDataMap[NeedToBeExcuted] = "0";
                }
                else
                {
                    context.JobDetail.JobDataMap[NeedToBeExcuted] = "1";
                }
            }
        }

        public void JobExecutionVetoed(IJobExecutionContext context)
        {
            // throw new NotImplementedException();
        }

        public void JobWasExecuted(IJobExecutionContext context, JobExecutionException jobException)
        {
            //   throw new NotImplementedException();
        }

        public string Name
        {
            get { return "HellppL>t"; }
        }
    }

    public class MyExceptionHandler : IExceptionHandler
    {
        public Exception HandleException(Exception exception, Guid handlingInstanceId)
        {
            Console.WriteLine(exception);
            Console.WriteLine(exception.StackTrace);
            return exception;
        }
    }

    public class Patient
    {
        public int ID { get; set; }
        public string Name { get; set; }
    }

    public class PatientMapper : IRowMapper<Patient>
    {
        public Patient MapRow(IDataRecord row)
        {
            Patient p = new Patient();
            p.ID = int.Parse(row["ID"] + "");
            //   p.Name = row["Name"] + "";
            return p;
        }
    }
}
